package main

import (
	"fmt"
	"os"
	"strconv"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "math",
	Short: "数学运算",
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	// 添加子命令
	rootCmd.AddCommand(addCmd)
	rootCmd.AddCommand(subtractCmd)
	rootCmd.AddCommand(multiplyCmd)
	rootCmd.AddCommand(divideCmd)
}

var addCmd = &cobra.Command{
	Use:   "add",
	Short: "加法",
	Args:  cobra.MinimumNArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		sum := 0
		for _, arg := range args {
			num, err := strconv.Atoi(arg)
			if err != nil {
				fmt.Printf("数据参数不合法: %s\n", arg)
				return
			}
			sum += num
		}
		fmt.Printf("答案: %d\n", sum)
	},
}

var subtractCmd = &cobra.Command{
	Use:   "subtract",
	Short: "减法",
	Args:  cobra.ExactArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		num1, err1 := strconv.Atoi(args[0])
		num2, err2 := strconv.Atoi(args[1])
		if err1 != nil || err2 != nil {
			fmt.Println("数据参数不合法")
			return
		}
		result := num1 - num2
		fmt.Printf("答案: %d\n", result)
	},
}

var multiplyCmd = &cobra.Command{
	Use:   "multiply",
	Short: "乘法",
	Args:  cobra.MinimumNArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		product := 1
		for _, arg := range args {
			num, err := strconv.Atoi(arg)
			if err != nil {
				fmt.Printf("数据参数不合法: %s\n", arg)
				return
			}
			product *= num
		}
		fmt.Printf("答案: %d\n", product)
	},
}

var divideCmd = &cobra.Command{
	Use:   "divide",
	Short: "除法",
	Args:  cobra.ExactArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		dividend, err1 := strconv.Atoi(args[0])
		divisor, err2 := strconv.Atoi(args[1])
		if err1 != nil || err2 != nil || divisor == 0 {
			fmt.Println("数据参数不合法")
			return
		}
		quotient := dividend / divisor
		remainder := dividend % divisor
		fmt.Printf("整数: %d, 余数: %d\n", quotient, remainder)
	},
}
